package com.csscaps.auth.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csscaps.auth.model.SysResource;
import com.csscaps.auth.model.SysRoleResource;
import com.csscaps.auth.service.SysI18nService;
import com.csscaps.auth.service.SysResourceService;
import com.csscaps.auth.service.SysRoleResourceService;
import com.csscaps.system.base.BaseTreeNode;
import com.csscaps.system.base.TreeNode;
import com.csscaps.system.shiro.ShiroUser;
import com.csscaps.system.utils.ResultUtil;
import com.csscaps.system.utils.StringUtils;
import com.csscaps.system.utils.UUIDGenerator;

 /**
 * @file  SysResourcecontroller.java
 * @author wanglei
 * @version 0.1
 * @todo	TODO
 * Copyright(C), 2015
 *			xi'an Coordinates Software Development Co., Ltd.
 * History
 *   	1. Date: 2016-07-23 04:37:01
 *      	Author: wanglei
 *      	Modification: this file was created
 *   	2. ...
 */
@Controller
@RequestMapping(value="/SysResource") 
public class SysResourceController{
    private final Log log = LogFactory.getLog(SysResourceController.class);
   
	
	@Autowired
	private SysResourceService sysResourceService;
	@Autowired
	private SysRoleResourceService sysRoleResourceService;
	@Autowired
	private SysI18nService sysI18nService;
 
	/**
	 * 新增
	 * @return
	 */
	@RequestMapping(value = "add", method=RequestMethod.POST)
	@ResponseBody
	public Map  add(@Valid  @RequestBody SysResource vo){
		
		Map resoultMap = null;
		try {
			vo.setResourceCreateTime(new Date());
			vo.setResourceUuid(UUIDGenerator.genUuidStr());
			Subject subject = SecurityUtils.getSubject();
            String userName = String.valueOf(((ShiroUser)subject.getPrincipal()).getUserAccount());
		    vo.setResourceCreateUser(userName);
		       
			sysResourceService.insertByVo(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	
	/**
	 * 修改
	 * @return
	 */
	@RequestMapping(value = "edit", method=RequestMethod.POST)
	@ResponseBody
	public Map  edit(@Valid  @RequestBody SysResource vo){
		
		Map resoultMap = null;
		try {
			sysResourceService.updateByVO(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	/**
	 * 删除
	 * @return
	 */
	@RequestMapping(value = "remove", method=RequestMethod.POST)
	@ResponseBody
	public Map  remove(@Valid  @RequestBody SysResource vo){
		
		Map resoultMap = null;
		try {
			sysResourceService.deleteByVo(vo);
			resoultMap = ResultUtil.getSuccessResult();
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	
	/**
	 * 查询
	 * @return
	 */
	@RequestMapping(value = "getAll/{language}")
	@ResponseBody
	public Map  getAll(@PathVariable ("language") String language){
		Map resoultMap = null;
		List<Object>  resouceNodeList = new ArrayList<Object>() ;
		try {
			List<SysResource> list =	sysResourceService.selectAll();
			list = resourceI18n(list, language);
			for(int i = 0; i<list.size();i++){
  				SysResource sysResource = list.get(i);
  				BaseTreeNode treeNode = new BaseTreeNode();
  				treeNode.setId(sysResource.getResourceUuid());
  				treeNode.setpId(sysResource.getResourceParentUuid());
  				treeNode.setName(sysResource.getResourceName());
  				resouceNodeList.add(treeNode);
  			}
  			resoultMap = ResultUtil.getSuccessResult(resouceNodeList);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	/**
	 * 根据条件查询
	 * @return
	 */
	@RequestMapping(value = "get", method=RequestMethod.POST)
	@ResponseBody
	public Map  get(@Valid  @RequestBody SysResource vo ){
		
		Map resoultMap = null;
		try {
			List<SysResource> list =	sysResourceService.selectByVo(vo);
			list = resourceI18n(list, vo.getLanguage());
			resoultMap = ResultUtil.getSuccessResult(list);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}
	
	
	/**
	 * 分页查询
	 * @return
	 */
/*	@RequestMapping(value = "getPage", method=RequestMethod.POST)
	@ResponseBody
	public Map  getPage(@Valid  @RequestBody SysResource vo){
		
		Map resoultMap = null;
		try {
			
			PageInfo<SysResource> pageInfo =	sysResourceService.selectPage(vo);
			resoultMap = ResultUtil.getSuccessResult(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		
		return resoultMap;
	}*/
	
	/**
	 * 删除资源信息
	 * @return
	 */
	@RequestMapping(value = "remove/{resourceUuid}", method=RequestMethod.GET)
	@ResponseBody
	public Map  removeByPk(@PathVariable ("resourceUuid") String  resourceUuid){
		Map resoultMap = null;
		try {
			//查看资源是否被角色使用
			SysRoleResource	roleResource = new SysRoleResource();
			roleResource.setRoleresourceResourceId(resourceUuid);
			List<SysRoleResource> list = sysRoleResourceService.selectByVo(roleResource);
			//查看资源知否有子资源
			SysResource sysResource = new SysResource();
			sysResource.setResourceParentUuid(resourceUuid);
			List<SysResource> childresource = sysResourceService.selectByVo(sysResource );
			  if(list.size()==0 && childresource.size() == 0){
					 //删除资源信息
					sysResourceService.deleteByPk(resourceUuid);
					resoultMap = ResultUtil.getSuccessResult();
				}else if (list.size() > 0) {
					resoultMap = ResultUtil.getErrorResult("该资源正在被角色使用！");
				}else if (childresource.size() > 0){
					resoultMap = ResultUtil.getErrorResult("该资源存在子资源,请先删除子资源！");
				}
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	
	
	/**
	 * 根据id 查询
	 * @return
	 */
	@RequestMapping(value = "getByPk/{resourceUuid}/{language}", method=RequestMethod.GET)
	@ResponseBody
	public Map  getByPk(@PathVariable ("resourceUuid") String  resourceUuid,@PathVariable ("language") String language){
		Map resoultMap = null;
		try {
			 SysResource sysResource = sysResourceService.selectByPk(resourceUuid) ;
			 Map map = sysI18nService.getI18nMap();
		     Map i18nMap	= (Map) map.get(sysResource.getId());
		     String name = String.valueOf(i18nMap.get(language));
		     sysResource.setResourceName(name);	
			 resoultMap = ResultUtil.getSuccessResult(sysResource);
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	
	/**
	 * 查询角色的资源信息-用户角色资源授权
	 * @param roleIDStr
	 * @return
	 */
	@RequestMapping(value = "getRoleResouse", method=RequestMethod.POST)
  	@ResponseBody
  	 
  	public Map<String, Object> getRoleResouse(@RequestBody Map<String, String> parameter ) {
  		Map resoultMap = null;
		try {
			String roleId = parameter.get("roleId") ;
			String language = parameter.get("language") ;
			List<Object> resouceTreeNode   = sysResourceService.getRoleResouse(roleId,language) ;
			 resoultMap = ResultUtil.getSuccessResult(resouceTreeNode);
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
  	}
	
	
  /**
 * 查询用户所拥有的资源-用于登陆后菜单初始化
 * @param
 * @return
 */
	@RequestMapping(value = "getUserResouse/{language}", method=RequestMethod.GET)
  	@ResponseBody
  	public Map<String, Object> getUserResouse(@PathVariable ("language") String language) {
  		Map resoultMap = null;
		try {
		  		     Subject subject = SecurityUtils.getSubject();
		  		     String userName = String.valueOf(((ShiroUser)subject.getPrincipal()).getUserAccount());
		  		     List<SysResource> resouceList = sysResourceService.selectResouseByUserAccount(userName);	
		  		     resouceList = resourceI18n(resouceList, language);
		  			 List<TreeNode> list = buildTree(resouceList);
		  			resoultMap = ResultUtil.getSuccessResult(list); 
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
  	}
	
	
	/**
	 * 查询用户的按钮权限，用户单页面初始化按钮权限使用
	 * @param  
	 * @return
	 */
	@RequestMapping(value = "getButtonResouce/{resourceTitle}/{language}", method=RequestMethod.GET)
	@ResponseBody
	public Map  getButtonResouce(@PathVariable ("resourceTitle") String resourceTitle,@PathVariable ("language") String language){
		Map resoultMap = null;
		try {
			 Subject subject = SecurityUtils.getSubject();
			 SysResource resource = new SysResource();
			 resource.setResourceTitle(resourceTitle);
  			 String userName = String.valueOf(((ShiroUser)subject.getPrincipal()).getUserAccount());
  			 resource.setUserName(userName);
  			 List<SysResource> list = sysResourceService.selectButtonByVO(resource);
  			 list = resourceI18n(list, language);
  			resoultMap = ResultUtil.getSuccessResult(list);
			} catch (Exception e) {
			e.printStackTrace();
			resoultMap = ResultUtil.getErrorResult();
		}
		return resoultMap;
	}
	
	public List<SysResource> resourceI18n(List<SysResource> list,String language) {
		Map map = sysI18nService.getI18nMap();
		List<SysResource> resoultList = new ArrayList<>(); 
		for (SysResource sysResource : list) {
		   Map i18nMap	= (Map) map.get(sysResource.getId());
		   String name = String.valueOf(i18nMap.get(language));
		   sysResource.setResourceName(name);
		   resoultList.add(sysResource);
		}
		return resoultList;
	}
	
	
	   public  List<TreeNode> buildTree(List<SysResource> list){
	          List<TreeNode> roots = new ArrayList<TreeNode>();
	          Hashtable<String,TreeNode> resouceTable = new Hashtable<String,TreeNode>();
	          for (SysResource sysResource : list) {
	                TreeNode node = new TreeNode();
	                node.setId(sysResource.getResourceUuid());
	                node.setName(sysResource.getResourceName());
	                node.setParentId(sysResource.getResourceParentUuid());
	                node.setModule(sysResource.getResourceTitle());
	                node.setUrl(sysResource.getResourceUrl());
	                node.setSort(sysResource.getResourceNumber());
	                node.setIconUrl(sysResource.getResourceImage());
	                resouceTable.put(node.getId(), node);
	            }
	          Set<Entry<String, TreeNode>> entrySet = resouceTable.entrySet();
	          for (Entry<String, TreeNode> entry : entrySet) {
	                TreeNode node = entry.getValue();
	                    if(!StringUtils.isEmpty(node.getParentId())) { // 非根节点
	                        try {
	                            resouceTable.get(node.getParentId()).addChild(node);
	                        }catch (Exception e){
	                            continue;
	                        }
	                    }else{ //根节点
	                        roots.add(node);
	                    }
	            }
	        return roots;
	    }
	    
	   
}
